package com.salary.snippet

import java.util.Date

import scala.xml.{NodeSeq,Text}
import net.liftweb.http.{RequestVar,S,SHtml}
import net.liftweb.common.Full
import net.liftweb.util.Helpers.{bind,chooseTemplate}
import net.liftweb.util.Helpers._

import model.User


object Users {
	def show (xhtml : NodeSeq) : NodeSeq = {
		val users:List[User] = User.findAll
		users.flatMap({item => 
				bind("user", chooseTemplate("users", "entry", xhtml),
				"firstname" -> Text(item.firstName),
				"lastname" -> Text(item.lastName),
				"email" -> Text(item.email),
				"operation" -> Text(item.operation.toString),
                "actions" -> { SHtml.link("/viewUsers", () => item.delete_!, Text("Delete")) ++ Text(" ") ++
                               SHtml.link("/editUser", () => currentUserVar(item), Text("Edit")) })
			})

	}
	
	object currentUserVar extends RequestVar[User]({
		User.create
	})
	def currentUser = currentUserVar.is
	
	def edit(xhtml : NodeSeq) : NodeSeq = {
		var operation = ""

		def doSave () = {
		  currentUser.validate match {
			case Nil =>
			  currentUserVar.operation(operation.toInt).save
			  S.redirectTo("/viewUsers")
			case x => S.error(x)
		  }
		}

		val item = currentUser

		bind("em", xhtml,
			 "key" -> SHtml.hidden(() => currentUserVar(item)),
			 "firstname" -> SHtml.text(currentUserVar.firstName.toString, currentUserVar.firstName(_)),
			 "lastname" -> SHtml.text(currentUserVar.lastName.toString, currentUserVar.lastName(_)),
			 "email" -> SHtml.text(currentUserVar.email.toString, currentUserVar.email(_)),
			 "operation" -> SHtml.text(currentUserVar.operation.toString, operation = _),
			 "save" -> SHtml.submit("Save", doSave))
	}
}

